<template>
    <div class="detail-page">
        <div class="header">
            <mooc-detail-header :data="covertData(detail, 'header')"/>
        </div>
        <div class="main-content">
            <van-tabs v-model:active="active" scrollspy sticky ref="vanTabRef">
                <van-tab title="简介">
                    <div class="module">
                        <introduct :data="covertData(detail, 'intro')"/>
                    </div>
                </van-tab>
                <van-tab :title="`评价 ${page.total}`">
                    <div class="module">
                        <Comment
                            :list="comments"
                            :data="covertData(detail, 'comment')"
                            :page="page.pageIndex"
                            :total="page.total"
                            :finished="finished"
                            :loading="commentLoading"
                            @load-data="loadMore"
                        />
                    </div>
                </van-tab>
            </van-tabs>
        </div>
    </div>
</template>

<script setup>
import moocDetailHeader from './components/mooc-detail-header.vue'
import Comment from './pane/comment.vue'
import introduct from './components/introduction.vue'
import {computed, onMounted, ref, watch, reactive, nextTick, onUnmounted} from 'vue';
import envJudge from '@/lib/judge-env';
import {useStore} from 'vuex'
import {useRoute} from 'vue-router';
import { handleErrorPage } from '@/lib/tools.js';

const route = useRoute();
const store = useStore();
const env = envJudge();
const isApp = reactive(['IOS', 'android'].includes(env));
const active = ref(0)
const vanTabRef = ref(null) // tab标签实例
// 慕课详情数据
const detail = ref();
const comments = ref([]); // 评论列表
const page = reactive({ // 评论参数
    pageIndex: 1,
    pageSize: 10,
    total: 0
});
const finished = ref(true); // 评论是否有更多
const commentLoading = ref(true);
const showTab = ref(false) // 显示tab时设置app标题

watch(() => showTab.value, (val) => {
    if(isApp) setAppTitle()
})

// 获取慕课详情
async function getMoocDetail () {
    try {
        let res = await  G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })
        detail.value = res.data || {};
        getComments();
        // 不是购买者 并且不是创建人
        let notCourseUser = !detail.value?.isBuy && !detail.value?.isMyCreate;
        
        let isPublish = detail.value?.publishState == 1 && detail.value?.state == 4;

        // 课程未发布 只有创建人能看 已报名的人也能看
        if (!isPublish && notCourseUser) {
            handleErrorPage('unpublished', route.params.moocId);
        }
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            handleErrorPage('delete', route.params.moocId);
        } else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

// 转换详情数据分发各个组件需要的值
function covertData(data = {}, type){
    // console.log(data, 'data')
    let keyMap = {
        header: ['title', 'cover', 'classifyList', 'courseWareCount', 'score', 'buyUserCount', 'completeHomeworkCount', 'completeCourseWareCount', 'homeworkCount', 'classHour'],
        intro: ['description', 'courseList'],
        comment: ['assessAppraiseId', 'courseList'],
        catalogue: ['courseList']
    }
    let formatObj = {}
    keyMap[type].forEach(item => {
        formatObj[item] = data[item]
    })
    console.log(formatObj)
    return formatObj
}

function loadMore(pageIndex){
    page.pageIndex = pageIndex
    getComments()
}

// 获取评论列表
function getComments() {
    commentLoading.value = true;
    G_transmit('courseCommentList', {
        data: {
            moocId: route.params.moocId,
            pageIndex: page.pageIndex,
            pageSize: page.pageSize,
            assessAppraiseId: detail.value.assessAppraiseId
        }
    }).then(({ data }) => {
        if (page.pageIndex <= 1) {
            comments.value = data.rows || [];
        } else {
            comments.value = comments.value.concat(data.rows || []);
        }
        page.total = data.total;

        finished.value = ((data.rows && data.rows?.length || 0) < page.pageSize);
        // setTimeout(() => {
            commentLoading.value = false;
        // }, 10);
    });
}

function scrollFn() {
    let tab = document.querySelector('.main-content .van-sticky')
    let header = document.querySelector('.header')
    if (!tab) return
    let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
    showTab.value = scrollTop >= header.clientHeight
    if ( scrollTop <= header.clientHeight + 150) {
        tab.style.display = 'none'
    }else{
        tab.style.display = 'block'
        nextTick(() => {
            vanTabRef.value && vanTabRef.value.resize()
        })
    }
}

function setAppTitle(){
    store.dispatch('jsBridge/disposeBridge', {
        method: 'setNativeTitle',
        options: {
            title: showTab.value ? detail.value.title : '',
            naviBarHidden: false,
            showBack: true
        }
    });
}

onMounted(() => {
    getMoocDetail();
    window.addEventListener('scroll', scrollFn, true);
})
onUnmounted(() => {
    window.removeEventListener('scroll', scrollFn)
})
</script>

<style lang="scss" scoped>
.detail-page {
    font-family: PingFangSC-Regular, PingFang SC;
    background-color: #fff;
    width:100%;
    min-height: 100vh;
    height:100%;
    .module{
        border-top: 10px solid #F5F5F5;
    }
}
:deep(.main-content){
        .van-tab {
            // font-size: 15px;
            // font-weight: 400;
            // color: #6E7074;
            // line-height: 24px;
        }
        .van-sticky{
            display: none;
        }
        .van-tab--active {
            font-size: 18px;
            font-weight: 600;
            color: #171A1D;
        }
        .van-tabs__line {
            width: 24px;
            height: 3px;
            background: linear-gradient(270deg, #00BDFE 0%, #0084F6 100%);
            border-radius: 2px;
            // bottom: 8px;
        }
    }

</style>
